<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>校区管理</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="/common/plugins/element-plus/index.css" />
    <!-- Iconify 图标 -->
    <script src="/common/plugins/iconify/iconify-icon.min.js"></script>
    <!-- Tailwind CSS -->
    <script src="/common/plugins/tailwindcss/tailwind.min.js"></script>
    <script src="/common/plugins/vue/vue.global.js"></script>
    <script src="/common/plugins/element-plus/index.full.js"></script>
    <script src="/common/plugins/axios/axios.min.js"></script>
    <script src="/common/js/axios-config.js"></script>
    <style>
        [v-cloak] {
            display: none;
        }

        body {
            margin: 0;
            padding: 16px;
            background-color: #f5f5f5;
        }
    </style>
</head>

<body class="bg-gray-50">
    <div id="app">
        <div id="page-management__campus" v-cloak>
            <!-- 工具栏：分为查询区和操作区 -->
            <div class="mb-5">
                <!-- 查询表单区 -->
                <div class="p-4 bg-white rounded-lg shadow mb-3">
                    <div class="flex items-center justify-between mb-2">
                        <h3 class="text-lg font-medium">查询条件</h3>
                    </div>
                    <el-form :inline="true">
                        <el-form-item label="校区名称">
                            <el-input v-model="searchParams.name" placeholder="请输入校区名称" clearable
                                style="width: 178px;"></el-input>
                        </el-form-item>
                        <el-form-item label="联系人">
                            <el-input v-model="searchParams.contactPerson" placeholder="请输入联系人" clearable
                                style="width: 178px;"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="handleSearch">
                                <iconify-icon icon="mdi:magnify" width="16" height="16" class="mr-1"></iconify-icon>搜索
                            </el-button>
                            <el-button @click="handleReset">
                                <iconify-icon icon="mdi:refresh" width="16" height="16" class="mr-1"></iconify-icon>重置
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>

                <!-- 操作区 -->
                <div class="p-4 bg-white rounded-lg shadow flex justify-between items-center">
                    <h3 class="text-lg font-medium">数据操作</h3>
                    <div>
                        <el-button type="primary" @click="handleAdd">
                            <iconify-icon icon="mdi:plus" width="16" height="16" class="mr-1"></iconify-icon>新增校区
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 校区表格 -->
            <div class="bg-white rounded-lg shadow p-4 mb-5">
                <div class="flex justify-between items-center mb-2">
                    <h3 class="text-lg font-medium">校区列表</h3>
                    <el-button size="small" @click="loadCampusList">
                        <iconify-icon icon="mdi:refresh" width="16" height="16" class="mr-1"></iconify-icon>刷新
                    </el-button>
                </div>
                <el-table :data="tableData" :border="true" v-loading="loading" style="width: 100%" empty-text="暂无校区数据"
                    class="w-full">
                    <el-table-column prop="id" label="ID" width="80"></el-table-column>
                    <el-table-column prop="name" label="校区名称"></el-table-column>
                    <el-table-column prop="address" label="地址"></el-table-column>
                    <el-table-column prop="contactPerson" label="联系人"></el-table-column>
                    <el-table-column prop="contactPhone" label="联系电话"></el-table-column>
                    <el-table-column prop="contactEmail" label="联系邮箱"></el-table-column>
                    <el-table-column prop="managerName" label="校区管理员"></el-table-column>
                    <el-table-column prop="createTime" label="创建时间"></el-table-column>
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="scope">
                            <div class="flex gap-2">
                                <el-button size="small" @click="handleEdit(scope.row)">
                                    <iconify-icon icon="mdi:pencil" width="16" height="16"
                                        class="mr-1"></iconify-icon>编辑
                                </el-button>
                                <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                                    <iconify-icon icon="mdi:delete" width="16" height="16"
                                        class="mr-1"></iconify-icon>删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <div class="mt-5 flex justify-end">
                    <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                        :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"></el-pagination>
                </div>
            </div>

            <!-- 新增/编辑对话框 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" :before-close="handleDialogClose">
                <el-form ref="campusFormRef" :model="campusForm" :rules="campusRules" label-width="100px">
                    <el-form-item label="校区名称" prop="name">
                        <el-input v-model="campusForm.name" placeholder="请输入校区名称"></el-input>
                    </el-form-item>
                    <el-form-item label="地址" prop="address">
                        <el-input v-model="campusForm.address" placeholder="请输入地址"></el-input>
                    </el-form-item>
                    <el-form-item label="联系人" prop="contactPerson">
                        <el-input v-model="campusForm.contactPerson" placeholder="请输入联系人"></el-input>
                    </el-form-item>
                    <el-form-item label="联系电话" prop="contactPhone">
                        <el-input v-model="campusForm.contactPhone" placeholder="请输入联系电话"></el-input>
                    </el-form-item>
                    <el-form-item label="联系邮箱" prop="contactEmail">
                        <el-input v-model="campusForm.contactEmail" placeholder="请输入联系邮箱"></el-input>
                    </el-form-item>
                    <el-form-item label="校区管理员" prop="managerId">
                        <el-select v-model="campusForm.managerId" placeholder="请选择校区管理员" clearable filterable>
                            <el-option v-for="manager in managerOptions" :key="manager.id"
                                :label="manager.realName || manager.username" :value="manager.id"
                                :disabled="isManagerDisabled(manager.id)">
                                <span>{{ manager.realName || manager.username }}</span>
                                <span style="color: #8492a6; font-size: 13px; float: right;">{{ manager.username
                                    }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="flex justify-end gap-2">
                        <el-button @click="handleDialogClose">
                            <iconify-icon icon="mdi:close" width="16" height="16" class="mr-1"></iconify-icon>取消
                        </el-button>
                        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
                            <iconify-icon icon="mdi:content-save" width="16" height="16" class="mr-1"></iconify-icon>{{
                            isEdit ? '更新' : '创建' }}
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
    </div>

    <script>
        const { createApp, ref, reactive, onMounted } = Vue;

        const app = createApp({
            data() {
                return {
                    // 查询参数
                    searchParams: {
                        name: "",
                        contactPerson: ""
                    },
                    // 表格数据
                    tableData: [],
                    loading: false,
                    // 分页参数
                    pagination: {
                        pageNum: 1,
                        pageSize: 10,
                        total: 0
                    },
                    // 对话框相关
                    dialogVisible: false,
                    dialogTitle: "新增校区",
                    isEdit: false,
                    submitLoading: false,
                    // 表单数据
                    campusForm: {
                        id: undefined,
                        name: "",
                        address: "",
                        contactPerson: "",
                        contactPhone: "",
                        contactEmail: "",
                        managerId: undefined
                    },
                    // 管理员选项
                    managerOptions: [],
                    // 表单验证规则
                    campusRules: {
                        name: [
                            { required: true, message: "请输入校区名称", trigger: "blur" },
                            { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
                        ],
                        address: [
                            { max: 255, message: "长度不能超过 255 个字符", trigger: "blur" }
                        ],
                        contactPerson: [
                            { max: 50, message: "长度不能超过 50 个字符", trigger: "blur" }
                        ],
                        contactPhone: [
                            { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
                        ],
                        contactEmail: [
                            { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
                        ]
                    }
                };
            },

            methods: {
                // 加载校区列表
                async loadCampusList() {
                    this.loading = true;
                    try {
                        const response = await apiClient.post('/campus/search', {
                            pageNum: this.pagination.pageNum,
                            pageSize: this.pagination.pageSize,
                            params: this.searchParams
                        });

                        if (response.code === 200) {
                            this.tableData = response.data.list || [];
                            this.pagination.total = response.data.total || 0;
                        } else {
                            this.$message.error(response.message || '获取校区列表失败');
                        }
                    } catch (error) {
                        console.error('获取校区列表失败:', error);
                        this.$message.error('获取校区列表失败');
                    } finally {
                        this.loading = false;
                    }
                },

                // 管理员禁用逻辑
                isManagerDisabled(managerId) {
                    // 如果是编辑状态且当前校区已绑定此管理员，则不禁用
                    if (this.isEdit && this.campusForm.managerId === managerId) {
                        return false;
                    }

                    // 检查是否有其他校区已绑定此管理员
                    return this.tableData.some(campus =>
                        campus.managerId === managerId &&
                        campus.id !== this.campusForm.id // 排除当前编辑的校区
                    );
                },

                // 加载管理员选项
                async loadManagerOptions() {
                    try {
                        const response = await apiClient.post('/users/search', {
                            pageNum: 1,
                            pageSize: 1000,
                            params: {
                                userRole: 2, // 校区管理员
                                userStatus: 1 // 正常状态
                            }
                        });

                        if (response.code === 200) {
                            this.managerOptions = response.data.list || [];
                        }
                    } catch (error) {
                        console.error('获取管理员列表失败:', error);
                    }
                },

                // 查询
                handleSearch() {
                    this.pagination.pageNum = 1;
                    this.loadCampusList();
                },

                // 重置
                handleReset() {
                    this.searchParams = {
                        name: "",
                        contactPerson: ""
                    };
                    this.pagination.pageNum = 1;
                    this.loadCampusList();
                },

                // 分页大小变化
                handleSizeChange(val) {
                    this.pagination.pageSize = val;
                    this.pagination.pageNum = 1;
                    this.loadCampusList();
                },

                // 当前页变化
                handleCurrentChange(val) {
                    this.pagination.pageNum = val;
                    this.loadCampusList();
                },

                // 新增
                handleAdd() {
                    this.isEdit = false;
                    this.dialogTitle = "新增校区";
                    this.resetForm();
                    this.dialogVisible = true;
                },

                // 编辑
                handleEdit(row) {
                    this.isEdit = true;
                    this.dialogTitle = "编辑校区";
                    this.campusForm = { ...row };
                    this.dialogVisible = true;
                },

                // 删除
                handleDelete(row) {
                    this.$confirm(`确定要删除校区"${row.name}"吗？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(async () => {
                        try {
                            const response = await apiClient.delete(`/campus/${row.id}`);
                            if (response.code === 200) {
                                this.$message.success('删除成功');
                                this.loadCampusList();
                            } else {
                                this.$message.error(response.message || '删除失败');
                            }
                        } catch (error) {
                            console.error('删除校区失败:', error);
                            this.$message.error('删除失败');
                        }
                    });
                },

                // 提交表单
                async handleSubmit() {
                    try {
                        const valid = await this.$refs.campusFormRef.validate();
                        if (!valid) return;

                        this.submitLoading = true;

                        let response;
                        if (this.isEdit) {
                            response = await apiClient.put(`/campus/${this.campusForm.id}`, this.campusForm);
                        } else {
                            response = await apiClient.post('/campus', this.campusForm);
                        }

                        if (response.code === 200) {
                            this.$message.success(this.isEdit ? '更新成功' : '创建成功');
                            this.dialogVisible = false;
                            this.loadCampusList();
                        } else {
                            this.$message.error(response.message || '操作失败');
                        }
                    } catch (error) {
                        console.error('提交失败:', error);
                        this.$message.error('操作失败');
                    } finally {
                        this.submitLoading = false;
                    }
                },

                // 关闭对话框
                handleDialogClose() {
                    this.dialogVisible = false;
                    this.resetForm();
                },

                // 重置表单
                resetForm() {
                    this.campusForm = {
                        id: undefined,
                        name: "",
                        address: "",
                        contactPerson: "",
                        contactPhone: "",
                        contactEmail: "",
                        managerId: undefined
                    };
                    if (this.$refs.campusFormRef) {
                        this.$refs.campusFormRef.clearValidate();
                    }
                }
            },

            async mounted() {
                await this.loadManagerOptions();
                await this.loadCampusList();
            }
        });

        app.use(ElementPlus);
        app.mount("#page-management__campus");
    </script>
</body>

</html>